import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Response;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.odps.udf.UDF;
import com.aliyun.oss.OSSClient;

import redis.clients.jedis.Jedis;

/**
 * 下载海外商品图片
 * 
 * @author asus
 *
 */
public class TestUploadOverSeaImage extends UDF {
	private static final String redis_key = "oversea_image_url";
	private static Jedis jedis = RedisConfig.getJedis();
	private static OSSClient oss = OSSConfig.getImageOSSClient();
	private static String path = "Goods/source/";

	public static void main(String[] args) {
		test();
	}

	public static void test() {
		// lpop =
		// "{\"9eb6a7c9-c28c-43c2-99aa-d66f20bda8dd\":\"https://static.ewg.org/skindeep_images/6607/660777.png\"}";
		// while (true) {
		// 通过key循环取出redis中value
		// String lpop = jedis.lpop(redis_key);
		String lpop = "{\"url\": \"https://static.ewg.org/skindeep_images/972/97202.jpg\",\"uuid\": \"0efda948-b83c-45fd-b8a1-2afc2a315827\"}";
		try {
			/*
			 * if (StringUtils.isBlank(lpop)) { // 一直取到为空 break; }
			 */
			// 存的value为map形式 key为uuid，value为图片下载链接url
			JSONObject obj = JSONObject.parseObject(lpop);
			Iterator<Entry<String, Object>> iterator = obj.entrySet().iterator();
			String uuid = null;
			String imgUrl = null;
			while (iterator.hasNext()) {
				Entry<String, Object> next = iterator.next();
				// 图片保存名称
				String key = next.getKey();
				if (StringUtils.equalsIgnoreCase("uuid", key)) {
					uuid = next.getValue().toString();
				} else if (StringUtils.equalsIgnoreCase("url", key)) {
					imgUrl = next.getValue().toString();
				}
			}
			// 有的链接后面还带有参数 吧参数去掉
			if (StringUtils.isNotBlank(imgUrl) && imgUrl.contains("?")) {
				imgUrl = imgUrl.substring(0, imgUrl.indexOf("?"));
			}
			Response resultImageResponse = Jsoup.connect(imgUrl).ignoreContentType(true).execute();
			byte[] bodyAsBytes = resultImageResponse.bodyAsBytes();
			String suffix = imgUrl.substring(imgUrl.lastIndexOf("."));
			// 路径规则是oos文件夹路径+随机uuid—+文件后缀
			String finalPath = path + uuid + suffix;
			System.out.println(finalPath);
			// oss.putObject("bevol-static", finalPath, new
			// ByteArrayInputStream(bodyAsBytes));

			System.out.println("success");
		} catch (Exception e) {
			jedis.rpush(redis_key, lpop);
			System.out.println(lpop);
			e.printStackTrace();
		}
	}

	public static void test1() {
		// lpop =
		// "{\"9eb6a7c9-c28c-43c2-99aa-d66f20bda8dd\":\"https://static.ewg.org/skindeep_images/6607/660777.png\"}";
		while (true) {
			// 通过key循环取出redis中value
			String lpop = jedis.lpop(redis_key);
			try {
				if (StringUtils.isBlank(lpop)) {
					// 一直取到为空
					break;
				}
				// 存的value为map形式 key为uuid，value为图片下载链接url
				JSONObject obj = JSONObject.parseObject(lpop);
				Iterator<Entry<String, Object>> iterator = obj.entrySet().iterator();
				while (iterator.hasNext()) {
					Entry<String, Object> next = iterator.next();
					// 图片保存名称
					String uuid = next.getKey();
					String imgUrl = next.getValue().toString();
					// 图片可能包含多个链接 用逗号隔开 只下载第一张
					imgUrl = imgUrl.split(",")[0];
					// 有的链接后面还带有参数 吧参数去掉
					if (imgUrl.contains("?")) {
						imgUrl = imgUrl.substring(0, imgUrl.indexOf("?"));
					}
					// Response resultImageResponse =
					// Jsoup.connect(imgUrl).ignoreContentType(true).execute();
					// byte[] bodyAsBytes = resultImageResponse.bodyAsBytes();
					// String suffix = imgUrl.substring(imgUrl.lastIndexOf("."));
					// 路径规则是oos文件夹路径+随机uuid—+文件后缀
					// String finalPath = path + uuid + suffix;
					// oss.putObject("bevol-static", finalPath, new
					// ByteArrayInputStream(bodyAsBytes));
					// 构造URL
					URL url = new URL(imgUrl);
					HttpURLConnection con = (HttpURLConnection) url.openConnection();
					con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
					// 打开连接
					// URLConnection con = url.openConnection();
					// 设置请求超时为5s
					// con.setConnectTimeout(5 * 1000);
					// 输入流
					InputStream is = con.getInputStream();
					// 1K的数据缓冲
					byte[] bs = new byte[1024];
					// 读取到的数据长度
					int len;
					// 输出的文件流
					File sf = new File("E:\\overSeaPicture");
					if (!sf.exists()) {
						sf.mkdirs();
					}
					// 将url切割取个后缀
					String suffix = imgUrl.substring(imgUrl.lastIndexOf("."));
					// System.out.println(sf + "\\" + split[split.length - 1]);
					OutputStream os = new FileOutputStream(sf + "\\" + uuid + suffix);
					// 开始读取
					while ((len = is.read(bs)) != -1) {
						os.write(bs, 0, len);
					}
					// 完毕，关闭所有链接
					os.close();
					is.close();
				}
			} catch (Exception e) {
				jedis.rpush(redis_key, lpop);
				System.out.println(lpop);
				// e.printStackTrace();
			}
		}
	}

}
